Skip to content

Arrays

Alt text

1D array

  • An array is a data structure containing several elements of the same data type; these elements can be accessed using the same identifier name.
  • The position of each element in an array is identified using the array’s index.
  • The index of the first element in an array is the lower bound and the index of the last element is the upper bound.
  • The lower bound of an array is usually set as zero or one. Some programming languages can automatically set the lower bound of an array.

Alt text

DECLARE <identifier> : ARRAY[LB:UB] OF <data type>
DECLARE myList : ARRAY[0:8] OF INTEGER
myList[7] ← 16

2D array

  • A 2D array can be referred to as a table, with rows and columns.
  • Here is an example of a table with nine rows and three columns (27 elements) and lower bounds of zero.

Alt text

DECLARE <identifier> : ARRAY[LBR:UBR, LBC:UBC] OF <data type>
DECLARE myArray : ARRAY[0:8,0:2] OF INTEGER
myArray[7,0] ← 16

data structure

An is a data structure containing several elements of the same data type; these elements can be accessed using the same identifier name

[0/1]

Arrays

Which one is correct for declaring a 2D array?

[0/1]
  • To find an item stored in an array, the array needs to be searched.
  • One method of searching is a linear search.
  • Each element of the array is checked in order, from the lower bound to the upper bound, until the item is found or the upper bound is reached.

Alt text

DECLARE myList : ARRAY[0:23] OF CHAR
DECLARE item : CHAR
DECLARE flag : INTEGER
flag ← -1
item ← ’D’
FOR index ← 0 TO 23
      IF myList[index] = item THEN
      	flag ← index
      ENDIF
NEXT index
IF flag = -1 THEN
      OUTPUT ”Not found”
ELSE
      OUTPUT flag
ENDIF

Bubble sort

  • Lists can be more useful if the items are sorted in a meaningful order.
  • Each element of the array is compared with the next element and swapped if the elements are in the wrong order, starting from the lower bound and finishing with the element next to the upper bound.

Alt text

DECLARE myList : ARRAY[0:9] OF INTEGER
DECLARE temp : INTEGER
FOR i ← 0 TO 9
      FOR j ← 0 TO 9 - i
            IF myList[j] > myList[j+1]  THEN
                  temp = myList[j]
                  myList[j] = myList[j+1]
                  myList[j+1] = temp
            ENDIF
      NEXT j
NEXT i